#!/bin/sh

export PACKAGEMAKER=/Developer/Applications/Utilities/PackageMaker.app/Contents/MacOS/PackageMaker

REPLACE_VERSION=0

for arg in "$@"; do
	case "$arg" in
		-r|--r|--re|--rep|--repl|--repla|--replac|--replace)
			REPLACE_VERSION=1
			;;
		*)
			if [ -z "$INPUT" ]; then
				INPUT="$arg"
			elif [ -z "$OUTPUT" ]; then
				OUTPUT="$arg"
			else
				echo "warning: extra argument '$arg'"
			fi
			;;
	esac
done

ME=`dirname $0`
ME=`cd $ME; pwd`

if [ -z "$INPUT" ] || [ -z "$OUTPUT" ]; then
	echo "usage: [-r] $0 <input pmproj> <output pkg>"
	echo ""
	echo "  -r   replace version with current timestamp"
	echo ""
	exit 1
fi

die() {
	echo "failed: $@"
	exit 1
}


DATESTAMP=`date '+%Y%m%d'`
PACKAGENAME=`basename $INPUT | sed -e 's,.pmproj$,,'`
INPUTDIR=`dirname $INPUT`; INPUTDIR=`cd $INPUTDIR; pwd`
OUTPUTDIR=`dirname $OUTPUT`; OUTPUTDIR=`cd $OUTPUTDIR; pwd`
INPUTFILE=`basename $INPUT`
OUTPUTFILE=`basename $OUTPUT`

echo "* building $OUTPUTFILE"
$PACKAGEMAKER -build -p "$OUTPUT" -proj "$INPUT" || die "packagemaker returned non-zero"

echo "* adding datestamp to version"
PACKAGEVERSION=`/usr/bin/defaults read "$OUTPUTDIR/$OUTPUTFILE/Contents/Info" "CFBundleShortVersionString" 2>/dev/null`
if [ -n "$PACKAGEVERSION" ]; then
	if [ $REPLACE_VERSION -eq 1 ]; then
		/usr/bin/defaults write "$OUTPUTDIR/$OUTPUTFILE/Contents/Info" "CFBundleShortVersionString" "$DATESTAMP"
	else
		/usr/bin/defaults write "$OUTPUTDIR/$OUTPUTFILE/Contents/Info" "CFBundleShortVersionString" "$PACKAGEVERSION.$DATESTAMP"
	fi
	/usr/bin/plutil -convert xml1 "$OUTPUTDIR/$OUTPUTFILE/Contents/Info.plist"
	/bin/chmod a+r "$OUTPUTDIR/$OUTPUTFILE/Contents/Info.plist"
	echo "- updated"
else
	echo "- no version found"
fi
